/**
 * Copyright 2020 Inc.
 **/
package com.myz.buddy.interceptor;

import net.bytebuddy.implementation.bind.annotation.AllArguments;
import net.bytebuddy.implementation.bind.annotation.Origin;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;
import net.bytebuddy.implementation.bind.annotation.SuperCall;
import net.bytebuddy.implementation.bind.annotation.This;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Method;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.Callable;

/**
 * 委托类
 *
 * @author maoyz0621 on 2020/11/23
 * @version v1.0
 */
public class TimeInterceptor {

    /**
     * 拦截原有方法：@Origin
     *
     * @param method
     * @param callable
     * @return
     * @throws Exception
     */
    @RuntimeType
    public Object intercept(@This Object obj,
                            @Origin Method method,
                            @AllArguments Object[] args,
                            @SuperCall Callable<?> callable) throws Exception {

        String name = method.getName();
        if (StringUtils.equalsIgnoreCase(name, "equals")
                || StringUtils.equalsIgnoreCase(name, "hashCode")
                || StringUtils.equalsIgnoreCase(name, "toString")
                || obj.getClass().getName().startsWith("org.springframework")) {
            return callable.call();
        }
        System.out.println("^^^^^^^^^^^^^^^^^^^ TimeInterceptor.intercept start ^^^^^^^^^^^^^^^^^^^");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
        long start = System.currentTimeMillis();
        Object val = null;
        val = callable.call();
        // todo 记录日志
        System.out.println("TimeInterceptor.intercept: "
                + method.getDeclaringClass().getName() + "." + method.getName() + ": took " + (System.currentTimeMillis() - start) + "ms");
        return val;
    }
}